<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.1.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"lishx.com","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"hide","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="其中 1673 和 402、 1081 和 316 题只是换了说法而已，所以这里只有三道题。  316 去除重复字母（困难） 321 拼接最大数（困难） 402 移掉 K 位数字（中等） 1081 不同字符的最小子序列（中等） 1673 找出最具竞争力的子序列（中等）">
<meta property="og:type" content="article">
<meta property="og:title" content="单调栈解定长最小字典序问题">
<meta property="og:url" content="lishx.com/2020/12/03/algorithm/%E5%8D%95%E8%B0%83%E6%A0%88%E8%A7%A3%E6%9C%80%E5%B0%8F%E5%AD%97%E5%85%B8%E5%BA%8F%E9%97%AE%E9%A2%98/index.html">
<meta property="og:site_name" content="lishouxian&#39;s BLOG">
<meta property="og:description" content="其中 1673 和 402、 1081 和 316 题只是换了说法而已，所以这里只有三道题。  316 去除重复字母（困难） 321 拼接最大数（困难） 402 移掉 K 位数字（中等） 1081 不同字符的最小子序列（中等） 1673 找出最具竞争力的子序列（中等）">
<meta property="og:locale">
<meta property="og:image" content="https://gitee.com/lishouxian/blog-img/raw/master/2020-12/%E5%8D%95%E8%B0%83%E6%A0%88%E8%A7%A3%E5%AD%97%E5%85%B8%E5%BA%8F%E6%9C%80%E5%B0%8F%E9%97%AE%E9%A2%982.gif">
<meta property="og:image" content="https://gitee.com/lishouxian/blog-img/raw/master/2020-12/merge.gif">
<meta property="article:published_time" content="2020-12-03T02:00:00.000Z">
<meta property="article:modified_time" content="2020-12-03T13:15:57.208Z">
<meta property="article:author" content="李寿贤">
<meta property="article:tag" content="算法">
<meta property="article:tag" content="leetcode">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/lishouxian/blog-img/raw/master/2020-12/%E5%8D%95%E8%B0%83%E6%A0%88%E8%A7%A3%E5%AD%97%E5%85%B8%E5%BA%8F%E6%9C%80%E5%B0%8F%E9%97%AE%E9%A2%982.gif">

<link rel="canonical" href="lishx.com/2020/12/03/algorithm/%E5%8D%95%E8%B0%83%E6%A0%88%E8%A7%A3%E6%9C%80%E5%B0%8F%E5%AD%97%E5%85%B8%E5%BA%8F%E9%97%AE%E9%A2%98/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-Hans'
  };
</script>

  <title>单调栈解定长最小字典序问题 | lishouxian's BLOG</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">lishouxian's BLOG</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="lishx.com/2020/12/03/algorithm/%E5%8D%95%E8%B0%83%E6%A0%88%E8%A7%A3%E6%9C%80%E5%B0%8F%E5%AD%97%E5%85%B8%E5%BA%8F%E9%97%AE%E9%A2%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="李寿贤">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="lishouxian's BLOG">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          单调栈解定长最小字典序问题
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>
              

              <time title="Created: 2020-12-03 10:00:00 / Modified: 21:15:57" itemprop="dateCreated datePublished" datetime="2020-12-03T10:00:00+08:00">2020-12-03</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/algorithm/" itemprop="url" rel="index"><span itemprop="name">algorithm</span></a>
                </span>
            </span>

          
            <span id="/2020/12/03/algorithm/%E5%8D%95%E8%B0%83%E6%A0%88%E8%A7%A3%E6%9C%80%E5%B0%8F%E5%AD%97%E5%85%B8%E5%BA%8F%E9%97%AE%E9%A2%98/" class="post-meta-item leancloud_visitors" data-flag-title="单调栈解定长最小字典序问题" title="Views">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">Views: </span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine: </span>
    
    <a title="valine" href="/2020/12/03/algorithm/%E5%8D%95%E8%B0%83%E6%A0%88%E8%A7%A3%E6%9C%80%E5%B0%8F%E5%AD%97%E5%85%B8%E5%BA%8F%E9%97%AE%E9%A2%98/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2020/12/03/algorithm/%E5%8D%95%E8%B0%83%E6%A0%88%E8%A7%A3%E6%9C%80%E5%B0%8F%E5%AD%97%E5%85%B8%E5%BA%8F%E9%97%AE%E9%A2%98/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>其中 1673 和 402、 1081 和 316 题只是换了说法而已，所以这里只有三道题。</p>
<ul>
<li>316 去除重复字母（困难）</li>
<li>321 拼接最大数（困难）</li>
<li>402 移掉 K 位数字（中等）</li>
<li>1081 不同字符的最小子序列（中等）</li>
<li>1673 找出最具竞争力的子序列（中等）</li>
</ul>
<a id="more"></a>

<h3 id="402-移掉K位数字"><a href="#402-移掉K位数字" class="headerlink" title="402. 移掉K位数字"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/remove-k-digits/">402. 移掉K位数字</a></h3><h4 id="题目描述："><a href="#题目描述：" class="headerlink" title="题目描述："></a>题目描述：</h4><p>给定一个以字符串表示的非负整数 <em>num</em>，移除这个数中的 <em>k</em> 位数字，使得剩下的数字最小。</p>
<p><strong>注意:</strong></p>
<ul>
<li><em>num</em> 的长度小于 10002 且 ≥ <em>k。</em></li>
<li><em>num</em> 不会包含任何前导零。</li>
</ul>
<p><strong>示例 1 :</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">输入: num &#x3D; &quot;1432219&quot;, k &#x3D; 3</span><br><span class="line">输出: &quot;1219&quot;</span><br><span class="line">解释: 移除掉三个数字 4, 3, 和 2 形成一个新的最小的数字 1219。</span><br></pre></td></tr></table></figure>

<p><strong>示例 2 :</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">输入: num &#x3D; &quot;10200&quot;, k &#x3D; 1</span><br><span class="line">输出: &quot;200&quot;</span><br><span class="line">解释: 移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零。</span><br></pre></td></tr></table></figure>

<p>示例 <strong>3 :</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">输入: num &#x3D; &quot;10&quot;, k &#x3D; 2</span><br><span class="line">输出: &quot;0&quot;</span><br><span class="line">解释: 从原数字移除所有的数字，剩余为空就是0。</span><br></pre></td></tr></table></figure>

<h4 id="原理解析："><a href="#原理解析：" class="headerlink" title="原理解析："></a>原理解析：</h4><blockquote>
<p>贪心算法：</p>
<p>对于两个相同长度的数字序列，最左边不同的数字决定了这两个数字的大小。</p>
<p>例如，对于 A = caxxx，B = cbxxx，如果 a &gt; b 则 A &gt; B。</p>
</blockquote>
<p>基于此，我们可以知道，若要使得剩下的数字最小，需要保证靠前的数字尽可能小。</p>
<blockquote>
<p>单调栈：</p>
<p>首先我们需要知道栈的特点，就是先进先出，这个特性保证剩下的数字的有序性。</p>
<p>使用栈这样的数据结构，且当栈顶的元素小于当前元素才能进栈，否则弹出栈顶的元素。</p>
<p>这样保证了栈底的元素是最小的</p>
</blockquote>
<p>基于此，我们知道使用单调栈得到的数字字典序最小，但是可能剩余长度不满足要求</p>
<blockquote>
<p>最大弹出数：为保证剩余长度满足要求，这里有一个栈总体的最大弹出数字的要求，最多能弹出K次。</p>
</blockquote>
<h4 id="逻辑与伪代码"><a href="#逻辑与伪代码" class="headerlink" title="逻辑与伪代码"></a>逻辑与伪代码</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> 当前元素 <span class="keyword">in</span> 序列:</span><br><span class="line">    <span class="keyword">while</span> 剩余弹出次数 &gt; <span class="number">0</span> <span class="keyword">and</span> 栈 != null <span class="keyword">and</span> 栈顶元素 &gt; 当前元素:</span><br><span class="line">        栈.pop()</span><br><span class="line">        剩余弹出次数 -= <span class="number">1</span></span><br><span class="line">    栈.add(当前元素)</span><br><span class="line"><span class="keyword">return</span> 栈[:需要的长度]</span><br></pre></td></tr></table></figure>

<ol>
<li>自左至右准备将当前元素存入栈中。</li>
<li>如果栈顶元素大于当前元素且当前可弹出次数&gt; 0，则弹出栈顶元素，</li>
<li>重复步骤2，直至不满足步骤2条件。</li>
<li>将当前元素存入栈中。</li>
<li>回到步骤1。</li>
</ol>
<h4 id="动画解析"><a href="#动画解析" class="headerlink" title="动画解析"></a>动画解析</h4><p><img src="https://gitee.com/lishouxian/blog-img/raw/master/2020-12/%E5%8D%95%E8%B0%83%E6%A0%88%E8%A7%A3%E5%AD%97%E5%85%B8%E5%BA%8F%E6%9C%80%E5%B0%8F%E9%97%AE%E9%A2%982.gif" alt="单调栈解字典序最小问题2"></p>
<h4 id="Python代码"><a href="#Python代码" class="headerlink" title="Python代码"></a>Python代码</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">removeKdigits</span>(<span class="params">self, num: str, k: int</span>) -&gt; str:</span></span><br><span class="line">        res = []</span><br><span class="line">        remain = len(num) - k</span><br><span class="line">        <span class="keyword">for</span> n <span class="keyword">in</span> num:</span><br><span class="line">            <span class="keyword">while</span> k <span class="keyword">and</span> res <span class="keyword">and</span> res[<span class="number">-1</span>] &gt; n:</span><br><span class="line">                res.pop()</span><br><span class="line">                k -= <span class="number">1</span></span><br><span class="line">            res.append(n)</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;&#x27;</span>.join(res[:remain]).lstrip(<span class="string">&#x27;0&#x27;</span>) <span class="keyword">or</span> <span class="string">&#x27;0&#x27;</span></span><br></pre></td></tr></table></figure>

<h4 id="注意要点"><a href="#注意要点" class="headerlink" title="注意要点"></a>注意要点</h4><ol>
<li>在判断栈顶元素是否大于当前进栈元素时，要先判断栈是否为空，否则会有空指针异常。</li>
<li>在结果输出时要注意输出的长度和栈为空时的输出值。</li>
</ol>
<h3 id="316-去除重复字母"><a href="#316-去除重复字母" class="headerlink" title="316. 去除重复字母"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/remove-duplicate-letters/">316. 去除重复字母</a></h3><h4 id="题目描述"><a href="#题目描述" class="headerlink" title="题目描述"></a>题目描述</h4><p>给你一个字符串 <code>s</code> ，请你去除字符串中重复的字母，使得每个字母只出现一次。需保证 <strong>返回结果的字典序最小</strong>（要求不能打乱其他字符的相对位置）。</p>
<p><strong>示例 1：</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">输入：s &#x3D; &quot;bcabc&quot;</span><br><span class="line">输出：&quot;abc&quot;</span><br></pre></td></tr></table></figure>

<p><strong>示例 2：</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">输入：s &#x3D; &quot;cbacdcbc&quot;</span><br><span class="line">输出：&quot;acdb&quot;</span><br></pre></td></tr></table></figure>

<p><strong>提示：</strong></p>
<ul>
<li><code>1 &lt;= s.length &lt;= 104</code></li>
<li><code>s</code> 由小写英文字母组成</li>
</ul>
<h4 id="原理解析"><a href="#原理解析" class="headerlink" title="原理解析"></a>原理解析</h4><blockquote>
<p>最大弹出数：为保证剩余每个字母都出现一次，需要统计每个字母的最大弹出数，使用哈希表来存储。</p>
</blockquote>
<blockquote>
<p>每个字母只出现一次：保证每个字母在栈中只出现一次，可以使用一个哈希表来存储栈中的对应元素。</p>
</blockquote>
<h4 id="逻辑与伪代码-1"><a href="#逻辑与伪代码-1" class="headerlink" title="逻辑与伪代码"></a>逻辑与伪代码</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> 当前元素 <span class="keyword">in</span> 序列:</span><br><span class="line">    <span class="keyword">if</span> 当前元素 <span class="keyword">not</span> <span class="keyword">in</span> 栈:</span><br><span class="line">        <span class="keyword">while</span> 栈顶元素剩余弹出次数 &gt; <span class="number">1</span> <span class="keyword">and</span> 栈 != null <span class="keyword">and</span> 栈顶元素 &gt; 当前元素:</span><br><span class="line">            栈.pop()</span><br><span class="line">        栈.add(当前元素)</span><br><span class="line">    当前元素剩余弹出次数 -= <span class="number">1</span></span><br><span class="line"><span class="keyword">return</span> 栈[:需要的长度]</span><br></pre></td></tr></table></figure>

<h4 id="Python代码-1"><a href="#Python代码-1" class="headerlink" title="Python代码"></a>Python代码</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">removeDuplicateLetters</span>(<span class="params">self, s: str</span>) -&gt; str:</span></span><br><span class="line">        stack = []</span><br><span class="line">        remain_count = collections.Counter(s)</span><br><span class="line">        <span class="keyword">for</span> c <span class="keyword">in</span> s:</span><br><span class="line">            <span class="keyword">if</span> c <span class="keyword">not</span> <span class="keyword">in</span> stack:</span><br><span class="line">                <span class="keyword">while</span> stack <span class="keyword">and</span> c &lt; stack[<span class="number">-1</span>] <span class="keyword">and</span> remain_count[stack[<span class="number">-1</span>]] &gt; <span class="number">0</span>:</span><br><span class="line">                    stack.pop()</span><br><span class="line">                stack.append(c)</span><br><span class="line">            remain_count[c] -= <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;&#x27;</span>.join(stack)</span><br></pre></td></tr></table></figure>

<h3 id="321-拼接最大数"><a href="#321-拼接最大数" class="headerlink" title="321. 拼接最大数"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/create-maximum-number/">321. 拼接最大数</a></h3><h4 id="题目描述-1"><a href="#题目描述-1" class="headerlink" title="题目描述"></a>题目描述</h4><p>给定长度分别为 <code>m</code> 和 <code>n</code> 的两个数组，其元素由 <code>0-9</code> 构成，表示两个自然数各位上的数字。现在从这两个数组中选出 <code>k (k &lt;= m + n)</code> 个数字拼接成一个新的数，要求从同一个数组中取出的数字保持其在原数组中的相对顺序。</p>
<p>求满足该条件的最大数。结果返回一个表示该最大数的长度为 <code>k</code> 的数组。</p>
<p><strong>说明:</strong> 请尽可能地优化你算法的时间和空间复杂度。</p>
<p><strong>示例 1:</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">输入:</span><br><span class="line">nums1 &#x3D; [3, 4, 6, 5]</span><br><span class="line">nums2 &#x3D; [9, 1, 2, 5, 8, 3]</span><br><span class="line">k &#x3D; 5</span><br><span class="line">输出:</span><br><span class="line">[9, 8, 6, 5, 3]</span><br></pre></td></tr></table></figure>

<p><strong>示例 2:</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">输入:</span><br><span class="line">nums1 &#x3D; [6, 7]</span><br><span class="line">nums2 &#x3D; [6, 0, 4]</span><br><span class="line">k &#x3D; 5</span><br><span class="line">输出:</span><br><span class="line">[6, 7, 6, 0, 4]</span><br></pre></td></tr></table></figure>

<p><strong>示例 3:</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">输入:</span><br><span class="line">nums1 &#x3D; [3, 9]</span><br><span class="line">nums2 &#x3D; [8, 9]</span><br><span class="line">k &#x3D; 3</span><br><span class="line">输出:</span><br><span class="line">[9, 8, 9]</span><br></pre></td></tr></table></figure>

<h4 id="原理解析-1"><a href="#原理解析-1" class="headerlink" title="原理解析"></a>原理解析</h4><blockquote>
<p>单调栈一分为二：两个单调栈的长度之和为合成的数组长度<code>k</code>，分别对两个数组进行上述两题的操作，获取两个单调栈。</p>
</blockquote>
<p>将两个单调栈合并得到最终结果，对比不同的单调栈长度分配方法，获得最优的结果</p>
<blockquote>
<p>使用归并排序中的<code>merge()</code> 方法来合并，两个单调栈</p>
</blockquote>
<h4 id="动画解析-1"><a href="#动画解析-1" class="headerlink" title="动画解析"></a>动画解析</h4><p><img src="https://gitee.com/lishouxian/blog-img/raw/master/2020-12/merge.gif" alt="merge"></p>
<h4 id="Python代码-2"><a href="#Python代码-2" class="headerlink" title="Python代码"></a>Python代码</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">maxNumber</span>(<span class="params">self, nums1, nums2, k</span>):</span></span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">max_stack</span>(<span class="params">nums, k</span>):</span></span><br><span class="line">            stack = []</span><br><span class="line">            remain = len(nums) - k</span><br><span class="line">            <span class="keyword">for</span> num <span class="keyword">in</span> nums:</span><br><span class="line">                <span class="keyword">while</span> remain <span class="keyword">and</span> stack <span class="keyword">and</span> stack[<span class="number">-1</span>] &lt; num:</span><br><span class="line">                    stack.pop()</span><br><span class="line">                    remain -= <span class="number">1</span></span><br><span class="line">                stack.append(num)</span><br><span class="line">            <span class="keyword">return</span> stack[:k]</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">merge</span>(<span class="params">A, B</span>):</span></span><br><span class="line">            res = []</span><br><span class="line">            <span class="keyword">while</span> A <span class="keyword">or</span> B:</span><br><span class="line">                bigger = A <span class="keyword">if</span> A &gt; B <span class="keyword">else</span> B</span><br><span class="line">                ans.append(bigger[<span class="number">0</span>])</span><br><span class="line">                bigger.pop(<span class="number">0</span>)</span><br><span class="line">            <span class="keyword">return</span> res</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> max(merge(max_stack(nums1, i), max_stack(nums2, k-i)) <span class="keyword">for</span> i <span class="keyword">in</span> range(k+<span class="number">1</span>) <span class="keyword">if</span> i &lt;= len(nums1) <span class="keyword">and</span> k-i &lt;= len(nums2))</span><br></pre></td></tr></table></figure>

<blockquote>
<p>参考：<a target="_blank" rel="noopener" href="https://leetcode-cn.com/u/fe-lucifer/">https://leetcode-cn.com/u/fe-lucifer/</a> </p>
</blockquote>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E7%AE%97%E6%B3%95/" rel="tag"># 算法</a>
              <a href="/tags/leetcode/" rel="tag"># leetcode</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/11/09/java/%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98/" rel="prev" title="线程的安全问题">
      <i class="fa fa-chevron-left"></i> 线程的安全问题
    </a></div>
      <div class="post-nav-item"></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#402-%E7%A7%BB%E6%8E%89K%E4%BD%8D%E6%95%B0%E5%AD%97"><span class="nav-number">1.</span> <span class="nav-text">402. 移掉K位数字</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%A2%98%E7%9B%AE%E6%8F%8F%E8%BF%B0%EF%BC%9A"><span class="nav-number">1.1.</span> <span class="nav-text">题目描述：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90%EF%BC%9A"><span class="nav-number">1.2.</span> <span class="nav-text">原理解析：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%80%BB%E8%BE%91%E4%B8%8E%E4%BC%AA%E4%BB%A3%E7%A0%81"><span class="nav-number">1.3.</span> <span class="nav-text">逻辑与伪代码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8A%A8%E7%94%BB%E8%A7%A3%E6%9E%90"><span class="nav-number">1.4.</span> <span class="nav-text">动画解析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Python%E4%BB%A3%E7%A0%81"><span class="nav-number">1.5.</span> <span class="nav-text">Python代码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%B3%A8%E6%84%8F%E8%A6%81%E7%82%B9"><span class="nav-number">1.6.</span> <span class="nav-text">注意要点</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#316-%E5%8E%BB%E9%99%A4%E9%87%8D%E5%A4%8D%E5%AD%97%E6%AF%8D"><span class="nav-number">2.</span> <span class="nav-text">316. 去除重复字母</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%A2%98%E7%9B%AE%E6%8F%8F%E8%BF%B0"><span class="nav-number">2.1.</span> <span class="nav-text">题目描述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90"><span class="nav-number">2.2.</span> <span class="nav-text">原理解析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%80%BB%E8%BE%91%E4%B8%8E%E4%BC%AA%E4%BB%A3%E7%A0%81-1"><span class="nav-number">2.3.</span> <span class="nav-text">逻辑与伪代码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Python%E4%BB%A3%E7%A0%81-1"><span class="nav-number">2.4.</span> <span class="nav-text">Python代码</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#321-%E6%8B%BC%E6%8E%A5%E6%9C%80%E5%A4%A7%E6%95%B0"><span class="nav-number">3.</span> <span class="nav-text">321. 拼接最大数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%A2%98%E7%9B%AE%E6%8F%8F%E8%BF%B0-1"><span class="nav-number">3.1.</span> <span class="nav-text">题目描述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90-1"><span class="nav-number">3.2.</span> <span class="nav-text">原理解析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8A%A8%E7%94%BB%E8%A7%A3%E6%9E%90-1"><span class="nav-number">3.3.</span> <span class="nav-text">动画解析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Python%E4%BB%A3%E7%A0%81-2"><span class="nav-number">3.4.</span> <span class="nav-text">Python代码</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">李寿贤</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">40</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">13</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">李寿贤</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a>
  </div>

        






<script>
  (function() {
    function leancloudSelector(url) {
      url = encodeURI(url);
      return document.getElementById(url).querySelector('.leancloud-visitors-count');
    }

    function addCount(Counter) {
      var visitors = document.querySelector('.leancloud_visitors');
      var url = decodeURI(visitors.id);
      var title = visitors.dataset.flagTitle;

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url })))
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length > 0) {
            var counter = results[0];
            leancloudSelector(url).innerText = counter.time + 1;
            Counter('put', '/classes/Counter/' + counter.objectId, { time: { '__op': 'Increment', 'amount': 1 } })
              .catch(error => {
                console.error('Failed to save visitor count', error);
              });
          } else {
              Counter('post', '/classes/Counter', { title, url, time: 1 })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }

    function showTime(Counter) {
      var visitors = document.querySelectorAll('.leancloud_visitors');
      var entries = [...visitors].map(element => {
        return decodeURI(element.id);
      });

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url: { '$in': entries } })))
        .then(response => response.json())
        .then(({ results }) => {
          for (let url of entries) {
            let target = results.find(item => item.url === url);
            leancloudSelector(url).innerText = target ? target.time : 0;
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }

    let { app_id, app_key, server_url } = {"enable":true,"app_id":"xb8ocBOeUvnh1ClRKD6b7Vwm-gzGzoHsz","app_key":"ODH211TGDI1jVYfBVxifNiXt","server_url":null,"security":false};
    function fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${api_server}/1.1${url}`, {
          method,
          headers: {
            'X-LC-Id'     : app_id,
            'X-LC-Key'    : app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      if (CONFIG.page.isPost) {
        if (CONFIG.hostname !== location.hostname) return;
        addCount(Counter);
      } else if (document.querySelectorAll('.post-title-link').length >= 1) {
        showTime(Counter);
      }
    }

    let api_server = app_id.slice(-9) !== '-MdYXbMMI' ? server_url : `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com`;

    if (api_server) {
      fetchData(api_server);
    } else {
      fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
        .then(response => response.json())
        .then(({ api_server }) => {
          fetchData('https://' + api_server);
        });
    }
  })();
</script>


      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>















  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : '9AvQGweVbH47hbtztejqnkta-gzGzoHsz',
      appKey     : 'lo0cfhvPh5MqPkgzHzT5n0Az',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
